import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCDemo2 {
    //查询操作
    public static void main(String[] args) throws SQLException {
        //通过控制台来进行其他查询
        Scanner in = new Scanner(System.in);
        System.out.println("请输入要查询的学生的学号：");
        int studentId = in.nextInt();
        //创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java108?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //建立连接和数据库
        Connection connection = dataSource.getConnection();
        //创建sql语句
        String sql = "select * from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,studentId);
        //执行sql语句,查询操作使用executeQuery,返回的是一个ResultSet类型的对象，表示了一个表格
        ResultSet resultSet = statement.executeQuery();
        //遍历表格:类似于迭代器
        while(resultSet.next()){
            //获取这一行的学号列
            int id = resultSet.getInt("id");
            //获取这一行的姓名列
            String name = resultSet.getString("name");
            System.out.println("id:"+id+",name:"+name);
        }
        //释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
